// pages/order/creatOrder/creatOrder.js
import getIn from '../../../sdk/utils/getIn';
import { API_CREAT_ORDER, API_CREAT_SPECUAL_ORDER, API_PRODUCT_LIST, API_SAVE_FORMID } from '../../../sdk/business/url';
import {SELECT_MAP, ARTICLE_DETAIL, ORDER_DETAIL, CREAT_ORDER_PRODUCT} from "../../../utils/url";
import { addNotifier, removeNotifier, notify } from "../../../sdk/utils/NotifyRegistryCenter.js";
import { getLocalTime, add0 } from '../../../sdk/utils/dateTool.js';
import {showSuccess, showFail} from '../../../utils/util';
import {TARIFF_DESCRIPTION_ID} from '../../../utils/config';
import { EXIT_PHONE } from '../../../utils/url';
Page({

  /**
   * 页面的初始数据
   */
  data: {
      carType:[
          { title: '标准货箱', id: 0, cover_picture: '/static/images/car1.png' },
          { title: '金杯', id: 1, cover_picture: '/static/images/car2.png' },
          { title: '电动货车', id: 2, cover_picture: '/static/images/car3.png' },
          { title: '劳务派遣', id: 3, cover_picture: '/static/images/car3.png' },
      ],
      currentIndex: 0,
      floorList:[['无电梯', '有电梯'], []],
      outIndex: [],
      inIndex: [],
      outAddress: {
          address: '',
          lat: "",
          lng: "",
          has_elevator: 0,
          floor_height: 0,
      },
      inAddress: {
          address: '',
          lat: "",
          lng: "",
          has_elevator: 0,
          floor_height: 0,
      },
      carNumList: [],
      carNum: 1,
      timeShow: false,
      focus: false, // textarea焦点
      remark: '',
      productList: [],
      sumPrice: 0, // 总价
      worktime: 2, // 派遣时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchData();
    const { floorList } = this.data;
    floorList[1] = Array.from({length:100}, (x,i) => `${i+1}层`);
    // 车辆数量选择
    const carNumList = Array.from({ length: 10 }, (x, i) => i + 1);
    // 时间选择
    const timestamp = new Date().getTime(); // 当前时间戳
    const hour = Array.from({ length: 23 }, (x, i) => add0(i)); // 小时列表
    const min = Array.from({ length: 60 }, (x, i) => add0(i));// 分钟列表
    const dayList = Array.from({ length: 5 }, (x, i) => getLocalTime(timestamp + i * 86400000, 'YY-MM-DD'));
    const timeList = [dayList, hour, min, hour, min,]
    // 初始化时分秒
    const hourList = getLocalTime(timestamp, 'hh-mm-ss').split(':');
    const houtDate = +hourList[0];
    const minDate = +hourList[1];
    const timeIndex = [0, houtDate, 0, minDate, 0, houtDate, 0, minDate];
    // 设备配置
    const phone = wx.getSystemInfoSync();
    this.setData({ floorList, carNumList, timeList, timeIndex, phone });
    addNotifier && addNotifier('updateAddress', this.updateAddress, this)
    addNotifier && addNotifier('updateProduct', this.updateProduct, this)
  },
  // 车型回调
  menuCallBackAction(e) {
      const index = getIn(e, ['detail']);
      const unsale_attrs = this.data.carType[index].unsale_attrs;
      this.setData({
          currentIndex: Number(index),
          unsale_attrs
      });
  },
  // 切换车型图片后的回调
  changeCurrent(e) {
    const current = getIn(e.detail, ['current']);
    const unsale_attrs = this.data.carType[current].unsale_attrs;
    this.setData({
        currentIndex: Number(current),
        unsale_attrs
    });
  },
  // 获取车型
  fetchData() {
      global.request(API_PRODUCT_LIST, {cate_nature:1}, (code, res)=>{
        if(code == 'SUCCESS') {
          const carType = getIn(res.data, ['list']);
          const unsale_attrs = carType[this.data.currentIndex].unsale_attrs;
          this.setData({ carType, unsale_attrs })
        }
      })
  },
    // 选择楼层
  bindMultiPickerChange(e) {
    const value = getIn(e.detail, ['value']);
    const key = getIn(e.currentTarget.dataset, ['key']);
    if (key == 'outIndex') {
        const outAddress = {...this.data.outAddress, has_elevator:value[0], floor_height: +value[1] + 1 }
        this.setData({ [key]: value, outAddress });
    } else {
        const inAddress = {...this.data.inAddress, has_elevator:value[0], floor_height: +value[1] + 1 }
        this.setData({ [key]: value, inAddress });
    }
  },
  // 跳转地图控件
  toMap(e) {
    const type = getIn(e.currentTarget.dataset, ['type']);
    const address = JSON.stringify(this.data[type]);
    global.navigateHelper.navigateTo({ pathname: SELECT_MAP, queryString: `type=${type}&address=${address}` });
  },
  // 修改租车数量
  changeCarNum(e) {
    const carNum = getIn(e.detail, ['value']);
    this.setData({ carNum: +carNum + 1 });
  },
  // 修改地址
  updateAddress(params) {
    const obj = { 
      ...this.data[params.key],
      address: params.address,
      lat: params.lat,
      lng: params.lng,
      addressVal: params.addressVal
    }
    this.setData({ [params.key]: obj })
  },
  updateProduct(params) {
      this.setData({ productList: params.paramsList, sumPrice: Number(params.price) })
  },
  // 弹出时间选择
  timeShow() {
    this.setData({ timeShow: true });
  },
  hiddenTime() {
    this.setData({ timeShow: false });
  },
  // 时间选择数组变化
  changeTime(e) {
    let value = e.detail.value;
      // 当前时间
    const timestamp = new Date().getTime();
    const hourList = getLocalTime(timestamp, 'hh-mm-ss').split(':');
    const houtDate = +hourList[0];
    const minDate = +hourList[1];
    if (value[0] == 0) {
        if (value[1] < houtDate) {
            value[1] = houtDate;
        } else if(value[3] < minDate) {
            value[3] = minDate;
        } else if(value[5] < houtDate) {
            value[5] = houtDate;
        } else if(value[7] < minDate) {
            value[7] = minDate;
        }
    }
    this.setData({ timeIndex: value });
  },
  // 记录预约时间
  updateTime() {
    const { timeList, timeIndex } = this.data;
    const outTime = `${timeList[0][timeIndex[0]]} ${timeList[1][timeIndex[1]]}:${timeList[2][timeIndex[3]]}:00`;
    const inTime = `${timeList[0][timeIndex[0]]} ${timeList[3][timeIndex[5]]}:${timeList[4][timeIndex[6]]}:00`;
    const start_time = new Date(outTime.replace(/-/g, '/')).getTime();
    const end_time = new Date(inTime.replace(/-/g, '/')).getTime();
    this.setData({ timeIndex, start_time, end_time, timeShow: false });
  },
  // 劳动力派遣时间段
  onChangWT(e) {
    const worktime = e.detail.value;
    this.setData({ worktime });
  },
  bindblur(e) {
    let worktime = e.detail.value;
    worktime = worktime == '' || worktime < 2 ? 2 : worktime;
    this.setData({ worktime });
  },
  // 提交订单
  submit(e){
    const token = wx.getStorageSync('token');
    const form_id = getIn(e.detail, ['formId']);
    const { carType, start_time, end_time, outAddress, inAddress, currentIndex, carNum, remark, worktime } = this.data;
    const params = {
      token,
      start_time,
      end_time,
      worktime,
      out: outAddress,
      in: inAddress,
      remark,
      product_list: [
        {
          product_id: carType[currentIndex].id,
          num: carNum
        },
        ...this.data.productList
      ]
    }
    const api = carType[currentIndex].id == 14 ? API_CREAT_SPECUAL_ORDER : API_CREAT_ORDER;
    global.request(API_SAVE_FORMID, { form_id, token });
    global.request(api, params, (code, res) => {
        if (code == 'SUCCESS') {
          global.navigateHelper.redirectTo({ pathname: ORDER_DETAIL, queryString: `order_id=${res.data}` });
        } else if(code == 'FAIL') {
          if (res.code == -80) {
            wx.showModal({
              title: '系统提示',
              content: res.msg,
              success(res) {
                if (res.confirm) {
                  global.navigateHelper.navigateTo({ pathname: EXIT_PHONE });
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {
            showFail(res.msg)
          }
        }
    })
  },
  // 留言
  onRemark(e) {
      const value = e.detail.value;
      this.setData({ remark: value });
  },
  // 留言点击聚焦（用以兼容textarea组件层级太高问题）
  toFocus() {
      this.setData({ focus: !this.data.focus });
  },
    // 费用详情
  toPrice() {
      const queryString = `id=${TARIFF_DESCRIPTION_ID}&cate_name=资费说明`;
      global.navigateHelper.navigateTo({ pathname: ARTICLE_DETAIL, queryString });
  },
  // 附加费用
  toProduct() {
      const paramsList = JSON.stringify(this.data.productList)
      global.navigateHelper.navigateTo({ pathname: CREAT_ORDER_PRODUCT, queryString: `paramsList=${paramsList}&sumPrice=${this.data.sumPrice}` });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    removeNotifier && removeNotifier('updateAddress', this.updateAddress, this)
    removeNotifier && removeNotifier('updateProduct', this.updateProduct, this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})